package api

import (
	"cloud-entropy-storage-system/common/pkg/msg"
	"cloud-entropy-storage-system/common/pkg/resp"
	"cloud-entropy-storage-system/server/internal/svc"
	"cloud-entropy-storage-system/server/internal/types/form"
	"github.com/asdine/storm/v3"
	"github.com/bluele/gcache"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strings"
)

type AdminLogic struct {
	log     *zap.Logger
	db      *storm.DB
	userSvc *svc.UserSvc
	gc      gcache.Cache
}

func NewAdminLogic(log *zap.Logger, db *storm.DB, gc gcache.Cache) *AdminLogic {
	return &AdminLogic{log: log, db: db, userSvc: svc.NewUserSvc(log, db, gc)}
}

func (a *AdminLogic) Login() gin.HandlerFunc {
	return func(c *gin.Context) {
		if a.userSvc.CheckIp(c.ClientIP()) {
			resp.ErrorResp(c).SetMsg(msg.GetMsg(msg.ErrorLoginIP)).WriteErrJsonExit(http.StatusBadRequest)
			return
		}
		username := strings.TrimSpace(c.PostForm("username"))
		password := strings.TrimSpace(c.PostForm("password"))
		if username != "" && password != "" {
			token, code := a.userSvc.Login(username, password, c)
			if code != msg.SUCCESS {
				a.userSvc.AddIPCount(c.ClientIP())
				resp.ErrorResp(c).SetMsg(msg.GetMsg(code)).WriteErrJsonExit(http.StatusBadRequest)
				return
			}
			resp.SuccessResp(c).SetData(token).WriteJsonExit()
		} else {
			resp.ErrorResp(c).SetMsg(msg.GetMsg(msg.ErrorLoginCheckRequired)).WriteErrJsonExit(http.StatusBadRequest)
			return
		}
	}
}

func (a *AdminLogic) Password() gin.HandlerFunc {
	return func(c *gin.Context) {
		var f form.Password
		if err := c.Bind(&f); err != nil {
			resp.ErrorResp(c).SetMsg(msg.GetMsg(msg.ErrorPwdBinding)).WriteJsonExit()
			return
		}
		if f.NewPwd != f.ConfirmPwd {
			resp.ErrorResp(c).SetMsg(msg.GetMsg(msg.ErrorPwdConfirm)).WriteJsonExit()
			return
		}
		if err := a.userSvc.ChangePwd(svc.GetUserId(c), f); err != nil {
			resp.ErrorResp(c).SetMsg(err.Error()).WriteJsonExit()
			return
		}
		if err := svc.SignOut(c); err != nil {
			resp.ErrorResp(c).SetMsg(err.Error()).WriteJsonExit()
			return
		}
		resp.SuccessResp(c).WriteJsonExit()
	}
}
